package ua.yandex.threadpool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ThreadPool {

    private BlockingQueue taskQueue = null;
    private List<PoolThread> threads = new ArrayList<PoolThread>();
    private boolean isStopped = false;

    public ThreadPool(int noOfThreads, int maxOfTask) {
        taskQueue = new ArrayBlockingQueue(maxOfTask);
        for (int i = 0; i < noOfThreads; i++) {
            threads.add(new PoolThread(taskQueue));
        }
    }

    public void go() {
        for (PoolThread thread : threads) {
            thread.start();
        }
    }

    public void execute(Runnable task) {
        if (this.isStopped) {
            throw new IllegalStateException("ThreadPool is stopped");
        }
        try {
            this.taskQueue.put(task);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void stop() {
        this.isStopped = true;
        for (PoolThread thread : threads) {
            thread.stopThread();
        }
    }
}
